package cn.ywrby.controller;

import cn.ywrby.domain.Apply;
import cn.ywrby.domain.ApplyProcess;
import cn.ywrby.domain.ApplyType;
import cn.ywrby.res.ResultResponse;
import cn.ywrby.service.ApplyService;
import cn.ywrby.utils.Constants;
import cn.ywrby.utils.JwtUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/applicant")
public class ApplyController {
    @Autowired
    ApplyService applyService;

    @GetMapping("/applytypes")
    public ResultResponse getApplyTypes(@RequestHeader("authorization") String token){
        //System.out.println(token);
        ResultResponse res=new ResultResponse();
        //验证token的合法和有效性
        String tokenValue= JwtUtils.verify(token);
        System.out.println(tokenValue);
        if(tokenValue!=null && tokenValue.startsWith(JwtUtils.TOKEN_SUCCESS)){
            //如果合法则获取用户信息
            String userId=tokenValue.replaceFirst(JwtUtils.TOKEN_SUCCESS,"");

            List<ApplyType> applyTypeList=applyService.getAllApplyTypes();
            res.setData(applyTypeList);
            res.setCode(Constants.STATUS_OK);
            res.setMessage(Constants.MESSAGE_OK);
        }else {
            //否则返回错误状态码
            res.setCode(Constants.STATUS_FAIL);
            res.setMessage(Constants.MESSAGE_FAIL);
        }

        return res;
    }

    @GetMapping("/applyList")
    public ResultResponse getApplyList(@RequestHeader("authorization") String token,
                                       @RequestParam("_limit") int pageSize,
                                       @RequestParam("_page") int pageId,
                                       @RequestParam("type") String type,
                                       @RequestParam("sort") String sort){
        //System.out.println(token);
        ResultResponse res=new ResultResponse();
        //验证token的合法和有效性
        String tokenValue= JwtUtils.verify(token);
        System.out.println(tokenValue);
        if(tokenValue!=null && tokenValue.startsWith(JwtUtils.TOKEN_SUCCESS)){
            //如果合法则获取用户信息
            String userId=tokenValue.replaceFirst(JwtUtils.TOKEN_SUCCESS,"");

            List<Apply> applyList=applyService.getApplyList(userId,pageId,pageSize,type);

            //获取分页信息对象
            PageInfo<Apply> info = new PageInfo<Apply>(applyList);

            res.setData(applyList);
            res.setCode(Constants.STATUS_OK);
            res.setMessage(Constants.MESSAGE_OK);
        }else {
            //否则返回错误状态码
            res.setCode(Constants.STATUS_FAIL);
            res.setMessage(Constants.MESSAGE_FAIL);
        }

        return res;
    }
}
